//
//  ViewController.swift
//  Phone
//
//  Created by redjun Z on 2019/1/30.
//  Copyright © 2019 network.xiaozhang.com. All rights reserved.
//

import UIKit
import AssetsLibrary

class ViewController: UIViewController {
    
    @IBOutlet weak var table: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        table.register(UINib(nibName: "PhoneListCell", bundle: nil), forCellReuseIdentifier: "iphoneCell")
        
        initData()
    }
    
    func initData(){
        //  获取本地的 联系人 所有的手机号
        phoneNumberArray = redLocationPhoneNumber() ?? []
        delay(UInt64(1.5)) { [weak self] in
            self?.table.reloadData()
        }
        
    }
    
    //MARK： -- 添加联系人
    @IBAction func addClick(_ sender: UIButton) {
        let xiangce = UIAlertAction(title: "相册", style: .default) { (btn) in
            let pickerCamera = UIImagePickerController()
            pickerCamera.delegate = self
            UIViewController.topViewController?.present(pickerCamera, animated: true, completion: nil)
        }
        let xiangji = UIAlertAction(title: "照相机📷", style: .default) { (btn) in
            let pickerPhoto = UIImagePickerController()
            pickerPhoto.sourceType = .camera
            pickerPhoto.delegate = self
            UIViewController.topViewController?.present(pickerPhoto, animated: true, completion: nil)
        }
        let _ = UIAlertExtension.showSystemAlert(title: "照片", message: "你想从相册选照片，还是想用照相机拍照片。", alertButtons: [xiangce,xiangji], preferredStyle: .alert)
    }
}

extension ViewController: UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return phoneNumberArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return CGFloat(App_height - APP_tabbarHeight)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "iphoneCell", for: indexPath) as? PhoneListCell
        if cell == nil {
            cell = Bundle.main.loadNibNamed("PhoneListCell", owner: nil, options: nil)?.last as? PhoneListCell
        }
        cell?.vc = self
        
//        获取图片地址
        if indexPath.row >= phoneNumberArray.count {
            print("数组越界了 \(phoneNumberArray.count)    \(indexPath.row)")
            return cell!
        }
        let key = phoneNumberArray[indexPath.row]
        let path =  getUserAddressBookPath(path: "AddressBookList") + "/" + "\(key).jpg"
//        从本地找图片
        locationfileiscache(filepath: getUserAddressBookPath(), fileName: "\(key).jpg") { (dataPath) in
            if let path = dataPath {
                cell!.userImg.image = UIImage(contentsOfFile: path)
            } else {
                print("key: \(key) value:\(String(describing: UserDefaults.standard.string(forKey: key)))")
                if let path = UserDefaults.standard.string(forKey: key) {
                    cell!.userImg.image = UIImage(contentsOfFile: path)
                } else {
                    print("❌❌❌ 没有找到图片 图片地址：\(path)")
                    cell!.userImg.image = UIImage(named: "me")
                }
            }
        }
        
        cell?.iphoneNumber.text = key
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}



extension String {
    func stringInterception(centerString str: Character,offset: Int,isUP: Bool) -> String? {
        if let ind = self.index(of: str) {
             let index = self.index(ind, offsetBy: 1)
            if isUP {
                return String(self[self.startIndex..<index])
            } else {
                return String(self[index..<self.endIndex])
            }
        } else {
            return self
        }
    }
}

extension ViewController :UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
//        var imageUrl = ""
//        print(info[UIImagePickerController.InfoKey.mediaURL] as Any)
//        print(info[UIImagePickerController.InfoKey.referenceURL] as Any)
//        print(info[UIImagePickerController.InfoKey.mediaMetadata] as Any)
//        if #available(iOS 11.0, *) {
//            print( info[UIImagePickerController.InfoKey.imageURL] as Any)
//            if picker.sourceType != .camera {
//                if let path: NSURL = info[UIImagePickerController.InfoKey.imageURL] as? NSURL {
////                    print("\(String(describing: path.absoluteString))")
////                    print("\(String(describing: path.relativeString))")
////                    print("\(String(describing: path.baseURL))")
////                    print("\(String(describing: path.absoluteURL))")
////                    print("\(String(describing: path.scheme))")
////                    print("\(String(describing: path.resourceSpecifier))")
////                    print("\(String(describing: path.host))")
////                    print("\(String(describing: path.user))")
////                    print("\(String(describing: path.relativePath))")
//
//                    let nameChar:Character = "e"
//                    imageUrl = (path.resourceSpecifier?.stringInterception(centerString: nameChar, offset: 1, isUP: false))!
//                    print(imageUrl)
//                }
//            }
//        } else {
//            // Fallback on earlier versions
//        }
//        拿到 原图
        let imagePickerc = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
        
        self.dismiss(animated: true) { [weak self] in
            //            输入手机号
            UIAlertExtension.showTextFieldAlert(title: "输入", message: "输入手机号", sureButtonTitle: "好了", otherButtons: nil, textFieldCall: { (textField) in
                textField.placeholder = "请输入手机号"
            }, callback: { (inputStr) in
                print("开始保存 联系人")
                guard let userNumberTemp = inputStr else {return}
                if userNumberTemp.count == 11 {
                    if baocunphotoLocation(data: nil, img: imagePickerc, nameImg: "\(userNumberTemp).jpg") {
                        print("保存到沙河成功 开始保存到 相册")
                        if picker.sourceType == .camera {
                                UIImageWriteToSavedPhotosAlbum(imagePickerc, nil, nil, nil)
                        }
                        //保存联系人 其实就是保存手机号
                        savePhone(number: userNumberTemp)
                        self?.initData()
                    } else {
                        print("保存 失败 ❌")
                        let button = UIAlertAction(title: "再试一次", style: .default)
                        let _ = UIAlertExtension.showSystemAlert(title: "❌保存失败", message: "再添加一次联系人", alertButtons: [button], preferredStyle: .alert)
                    }
                    
//                    if picker.sourceType == .camera {
//
//                    } else {
//                        //  保存键值对 key：手机号 value：图片在相册中的地址   当在沙河中找不到图片的时候 就去相册 获取图片
//                        print("key: \(userNumberTemp)")
//                        print("value: \(imageUrl)")
//                        if (imageUrl.count > 1) {
//                            savePhone(number: userNumberTemp)
//                            UserDefaults.standard.set(imageUrl, forKey: userNumberTemp)
//                            UserDefaults.standard.synchronize()
//                            self?.initData()
//                        } else {
//                            print("保存 失败 ❌")
//                            let button = UIAlertAction(title: "再试一次", style: .default)
//                            let _ = UIAlertExtension.showSystemAlert(title: "❌保存失败", message: "再添加一次联系人", alertButtons: [button], preferredStyle: .alert)
//                        }
//                    }
                } else {
                    let button = UIAlertAction(title: "手机号填错了", style: .default)
                    let _ = UIAlertExtension.showSystemAlert(title: "手机号错了❌", message: "再添加一次联系人", alertButtons: [button], preferredStyle: .alert)
                }
            })
        }
    }
    
    @objc func saveStatus(images: UIImage, didFinshSavingWithErr error: NSError) {
        if error != nil {
            print("❌ 保存到相册 失败 __\(error)")
        } else {
            print("保存到相册 成功")
        }
    }
    
}







//imagePickerc.saveImageToPHAsset(type: .Save, callBack: { (obj) in
//    if let imgObj = obj {
//        print("key: \(userNumberTemp)")
//        print("value: \(imgObj.adress)")
//        savePhone(number: userNumberTemp)
//        UserDefaults.standard.set(imgObj.adress, forKey: userNumberTemp)
//        UserDefaults.standard.synchronize()
//        self?.initData()
//    } else {
//        print("保存 失败 ❌")
//        let button = UIAlertAction(title: "再试一次", style: .default)
//        let _ = UIAlertExtension.showSystemAlert(title: "❌保存失败", message: "再添加一次联系人", alertButtons: [button], preferredStyle: .alert)
//    }
//})
